<script lang="ts" setup>
import type { OnActionClickParams } from '#/adapter/vxe-table';
import type { BaseinfoDemandApi } from '#/api/csyt/baseinfodemand';

import { h, nextTick, watch } from 'vue';

import { Plus } from '@vben/icons';

import { Button, Input, RadioGroup, Textarea } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getBaseinfoIndicatorListByDemandNo } from '#/api/csyt/baseinfodemand';
import { $t } from '#/locales';

import { useBaseinfoIndicatorGridEditColumns } from '../data';

const props = defineProps<{
  demandNo?: number; // 需求编码（主表的关联字段）
}>();

/** 表格操作按钮的回调函数 */
function onActionClick({
  code,
  row,
}: OnActionClickParams<BaseinfoDemandApi.BaseinfoIndicator>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useBaseinfoIndicatorGridEditColumns(onActionClick),
    border: true,
    showOverflow: true,
    autoResize: true,
    keepSource: true,
    rowConfig: {
      keyField: 'id',
    },
    pagerConfig: {
      enabled: false,
    },
    toolbarConfig: {
      enabled: false,
    },
  },
});

/** 添加需求指标 */
const onAdd = async () => {
  await gridApi.grid.insertAt({} as BaseinfoDemandApi.BaseinfoIndicator, -1);
};

/** 删除需求指标 */
const onDelete = async (row: BaseinfoDemandApi.BaseinfoIndicator) => {
  await gridApi.grid.remove(row);
};

/** 提供获取表格数据的方法供父组件调用 */
defineExpose({
  getData: (): BaseinfoDemandApi.BaseinfoIndicator[] => {
    const data =
      gridApi.grid.getData() as BaseinfoDemandApi.BaseinfoIndicator[];
    const removeRecords =
      gridApi.grid.getRemoveRecords() as BaseinfoDemandApi.BaseinfoIndicator[];
    const insertRecords =
      gridApi.grid.getInsertRecords() as BaseinfoDemandApi.BaseinfoIndicator[];
    return data
      .filter((row) => !removeRecords.some((removed) => removed.id === row.id))
      .concat(insertRecords.map((row: any) => ({ ...row, id: undefined })));
  },
});

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.demandNo,
  async (val) => {
    if (!val) {
      return;
    }
    await nextTick();
    await gridApi.grid.loadData(
      await getBaseinfoIndicatorListByDemandNo(props.demandNo!),
    );
  },
  { immediate: true },
);
</script>

<template>
  <Grid class="mx-4">
    <template #id="{ row }">
      <Input v-model:value="row.id" readonly />
    </template>
    <template #ruleName="{ row }">
      <Input v-model:value="row.ruleName" />
    </template>
    <template #ruleDescription="{ row }">
      <Textarea v-model:value="row.ruleDescription" />
    </template>
    <template #targetNo="{ row }">
      <Input v-model:value="row.targetNo" />
    </template>
    <template #targetName="{ row }">
      <Input v-model:value="row.targetName" />
    </template>
    <template #targetDescription="{ row }">
      <Textarea v-model:value="row.targetDescription" />
    </template>
    <template #status="{ row, column }">
      <RadioGroup v-model:value="row.status" :options="column.params.options" />
    </template>
    <template #flag="{ row, column }">
      <RadioGroup v-model:value="row.flag" :options="column.params.options" />
    </template>
  </Grid>
  <div class="-mt-4 flex justify-center">
    <Button
      :icon="h(Plus)"
      type="primary"
      ghost
      @click="onAdd"
      v-access:code="['csyt:baseinfo-demand:create']"
    >
      {{ $t('ui.actionTitle.create', ['需求指标']) }}
    </Button>
  </div>
</template>
